package com.gitee.zhuyunlong2018.mybatisplusrelations.handler;

import com.gitee.zhuyunlong2018.mybatisplusrelations.context.IContext;
import com.gitee.zhuyunlong2018.mybatisplusrelations.func.IGetter;

import java.util.HashMap;
import java.util.List;
import java.util.stream.Stream;


import static java.util.stream.Collectors.groupingBy;


public class ListBindOneHandler<T, R> extends ListHandler<T, R> {

    public ListBindOneHandler(IContext<T> context, IGetter<T, R> propertyGetter) {
        super(context, propertyGetter);
    }

    @SuppressWarnings({"rawtypes", "unchecked"})
    @Override
    protected void buildRelation() {
        if (foreignEntityList == null || foreignEntityList.isEmpty()) {
            return;
        }
        HashMap collect = (HashMap) foreignEntityList
                .stream()
                .collect(groupingBy(cache.getForeignPropertyGetter()));
        list.forEach(e -> {
            List<R> subList = (List<R>) collect.get(cache.getLocalPropertyGetter().apply(e));
            if (subList == null || subList.isEmpty()) {
                return;
            }
            if (streamStatus) {
                Stream<R> stream = getForeignStream(subList);
                // 有传入过滤器，进行过滤后取第一个
                R foreignEntity = stream
                        .findFirst()
                        .orElse(null);
                cache.getRelationEntitySetter().accept(e, foreignEntity);
            } else {
                cache.getRelationEntitySetter().accept(e, subList.get(0));
            }
        });
    }

}
